package com.sd.repay.task;

import com.sd.repay.common.Constants;
import com.sd.repay.pojo.ProfitDetail;
import com.sd.repay.service.BalanceOperService;
import com.sd.repay.service.ProfitDetailService;
import com.sd.repay.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author sd
 * @Description: 收益入账任务
 * @date 2018年09月29日
 */
@Component
public class ProfitToIncomeTask {

    private static Logger log = LoggerFactory.getLogger(ProfitToIncomeTask.class);

    @Autowired
    private ProfitDetailService profitDetailService;
    @Autowired
    private BalanceOperService balanceOperService;

    /**
     * 未入账的收益明细进行入账操作
     */
    public void executeProfitToIncome() throws Exception {
        log.info("--------收益入账任务开始执行---------");

        List<ProfitDetail> list = profitDetailService.getUnIncomeProfitDetail();
        log.info("需要入账的收益明细记录条数：" + list.size());

        String profitNo = "", profitMerType = "", profitMerNo = "", balanceService = "", balanceRemark = "";
        BigDecimal amount = BigDecimal.ZERO;

        for (ProfitDetail detail : list) {
            try {
                profitNo = detail.getProfitNo();
                profitMerType = detail.getProfitMerType();
                profitMerNo = detail.getProfitMerNo();

                if (Constants.PROFIT_SERVICE_QUICK_PAY.equals(detail.getServiceType()) || Constants.PROFIT_SERVICE_PERFECT_PAY.equals(detail.getServiceType())) {
                    balanceService = Constants.BALANCE_HIS_SERVICE_PROFIT;
                    balanceRemark = "商户交易分销收益定时任务入账";

                } else if (Constants.PROFIT_SERVICE_DISTRIB_PAY.equals(detail.getServiceType())) {
                    balanceService = Constants.BALANCE_HIS_SERVICE_TRADE;
                    balanceRemark = "代理商分润收益定时任务入账";

                } else {
                    //只有商户分销交易和代理商分润收益作此处理
                    continue;
                }

                log.info("收益明细编号[{}]准备入账", profitNo);
                balanceOperService.updateBalance(profitMerNo, profitMerType, amount, Constants.BALANCE_HIS_TRANS_TYPE_IN, Constants.BALANCE_HIS_TYPE_CURR,
                        Constants.BALANCE_HIS_SERVICE_PROFIT, profitNo, balanceRemark, Constants.BALANCE_CHANNEL_DAIFU);

            } catch (Exception e) {
                log.info("收益明细编号[{}]入账异常[{}]", new Object[]{profitNo, e});
                e.printStackTrace();
            }
        }

        log.info("-----------收益入账任务完成--------------");
        WebUtil.removeBlockTaskBySpringId(WebUtil.getClassSimpleName(this.getClass()));
    }
}